package com.zyd.controller.image;

import com.google.common.collect.Maps;
import com.zyd.constants.ErrorDef;
import com.zyd.io.vo.res.ResBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/images")
public class ImageContoller {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageContoller.class);

    @Value("${nginx.floder.url}")
    private String nginxUrl;

    @Value("${nginx.server.url}")
    private String imgeUrl;

    @PostMapping
    public ResBody uploadImage(@RequestBody Map<String, Object> map) throws Exception {
        OutputStream out;
        try {
            String imgBase64 = (String) map.get("imgBase64");
            String fileName = System.currentTimeMillis() + ".jpg";
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH )+1;
            String basePath2=nginxUrl+"/images";
            String basePath1=basePath2+"/"+year+"_"+month;
           String basePath = basePath1 + "/" + fileName;


            BASE64Decoder decoder = new BASE64Decoder();

            // Base64解码
            byte[] b = decoder.decodeBuffer(imgBase64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            File file2 = new File(basePath2);
            if (!file2.exists()){
                file2.mkdir();
            }

            File file1 = new File(basePath1);
            if (!file1.exists()){
                file1.mkdir();
            }

            File file = new File(basePath);
            if (!file.exists()) {
                file.createNewFile();
            }

            out = new FileOutputStream(basePath);
            out.write(b);
            out.flush();
            out.close();

            Map<String, Object> body = Maps.newHashMap();
            body.put("imgurl", imgeUrl+"/images/" +year+"_"+month+"/" +fileName);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "上传图片成功");
            resBody.setData(body);
            return resBody;
        } catch (Exception e) {
            LOGGER.error("上传图片失败", e);
           return  new ResBody(ErrorDef.UPLOAD_IMG_ERROR, "上传图片失败");
        }
    }
    @ResponseBody
    @PostMapping(value = "saveImg",produces = "application/json;charset=UTF-8")
    public  String fileSave(MultipartFile file){
        String filePath=null;
        //判断是否为空
        if(!file.isEmpty()){
            String fileName = null ;
            //获得文件类型
            String contentType=file.getContentType();
            //获得文件后缀名
            String suffixName=contentType.substring(contentType.indexOf("/")+1);
            //得到文件名
            fileName=System.currentTimeMillis()+"."+suffixName;
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH )+1;
            String basePath2=nginxUrl+"/images";
            String basePath1=basePath2+"/"+year+"_"+month+"/";
          String  basePath  = basePath1 + "/" + fileName;
            File file2 = new File(basePath2);
            if (!file2.exists()){
                file2.mkdir();
            }
            File file1 = new File(basePath1);
            if (!file1.exists()){
                file1.mkdir();
            }
            //文件保存路径
            try {
                //将文件转移到指定位置
                file.transferTo(new File(basePath));
                filePath="/images/" +year+"_"+month+"/" +fileName;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        Map<String, Object> body = Maps.newHashMap();
//        body.put("imgurl","c:/"+filePath );
//        ResBody resBody = new ResBody(ErrorDef.SUCCESS, "上传图片成功");
//        resBody.setData(body);
//        return resBody;
        return imgeUrl+filePath;

    }



}
